//toggle log window
#include "menuHandler.h"
#include <wx/button.h>
#include <wx/textctrl.h>
#include "redballDialog.h"
#include <wx/dialog.h>
#include <wx/hashmap.h>
#include <wx/choicdlg.h>
#include <wx/popupwin.h>
#include <wx/webview.h>
#include <wx/filesys.h>
#include <wx/fs_mem.h>
#include <wx/webviewarchivehandler.h>
#include <wx/filedlg.h>
#include <wx/txtstrm.h>
#include <wx/stream.h>
#include <wx/textfile.h>

void toggleLogWindow()
{
  if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }

    if(BFrame->split->IsSplit())
    {
       BFrame->split->Unsplit();
    }else
    {
    int gridW =getScreenWidth(),gridH =getScreenHeight() ;;
    //  BFrame->split->Initialize(BFrame->Grid1);
   //  BFrame->Grid1->SetMinSize(wxSize(gridW,gridH-120));
        BFrame->split->Hide();
    BFrame->split->SplitHorizontally(BFrame->Grid1, BFrame->logWin);
        BFrame->split->SetSashPosition(gridH*0.7);
        BFrame->split->Show();
//    BFrame->logWin->SetMinSize(wxSize(gridW,30));
//    BFrame->logWin->SetSize(gridW,30);
    }
    guess20101005(wxT("2010116"));
}

//保留当前一期的预测
void saveForecast()
{
  if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
 if(BFrame->saveForecastLight)return;//防止多次弹出
  BFrame->saveForecastLight=true;

  int row=BFrame->Grid1->GetCursorRow();

  if(row==0)
  {
     BFrame->saveForecastLight=false;
      return;
  }//不需要保存
  int cols=BFrame->Grid1->GetNumberCols();
  wxString result=wxEmptyString;
  wxString value=wxEmptyString;
  int count=0;
  for(int i=2;i<cols;i++)
   {
    value=BFrame->Grid1->GetCellValue(row,i);
    if(value!=wxEmptyString)
    {
        count++;
    if(i<cols-1)
      {
      result=result+value+wxT(",");
      }else
      {
        result=result+wxT("+")+value;
      }
    }
   }
//   if((result==wxEmptyString) || (count<6))
//     {
//      wxMessageBox(wxT("预测的号码不够!\n最少要6个才可以"));
//      BFrame->saveForecastLight=false;
//      return;
//     }
//insert into _notes(term,no,notes)
   wxString currentDate =BFrame->Grid1->GetCellValue(row,1);
   if(currentDate.IsEmpty())currentDate=getNextTermDate(BFrame->Grid1->GetCellValue(row,1));//term

   wxString currentOrder=BFrame->Grid1->GetCellValue(row,0);

  if(currentOrder.IsEmpty())
    {
   if(CHECK_YEAR_CHANGE(currentDate))
    {
       currentOrder=(currentDate.Mid(0,4));
       currentOrder=currentOrder+wxT("001");
    }else
    {
     currentOrder=getNextTermOrder(currentOrder);
    }

    }
   wxLogMessage(currentDate+wxT("\n")+currentOrder);
    //1is datetime

  DoubleBall* db =new DoubleBall();
 wxDialog dlg(BFrame, wxID_ANY, wxT("修改预测数据！"),
                 wxDefaultPosition, wxSize(500, 400));

  wxHtmlWindow* label= new wxHtmlWindow(&dlg, wxID_ANY,  wxPoint(10,5),wxSize(dlg.GetSize().GetWidth()-30, 30), wxHW_SCROLLBAR_NEVER);
  label->SetPage(wxT("<html><body><font color=red size=+1><b>预测期:<u>")+currentOrder+ wxT("</u><b></font></body></html>"));


   wxPanel* bgpanel=new wxPanel(&dlg, wxID_ANY, wxDefaultPosition, wxSize(dlg.GetSize().GetWidth(),dlg.GetSize().GetHeight()), wxTAB_TRAVERSAL|wxWANTS_CHARS, wxT("saveforcast"));
    wxButton* ok = new wxButton(bgpanel,wxID_OK,wxT("确定"),wxPoint(bgpanel->GetSize().GetWidth()/2-100,bgpanel->GetSize().GetHeight()-60));
    wxButton* cancle = new wxButton(bgpanel,wxID_CANCEL,wxT("取消"),wxPoint(bgpanel->GetSize().GetWidth()/2+10,bgpanel->GetSize().GetHeight()-60));

   wxTextCtrl* SQLTextBox=new wxTextCtrl(bgpanel, wxID_ANY, wxT(""),
                            wxPoint(10,40), wxSize(bgpanel->GetSize().GetWidth()-30,bgpanel->GetSize().GetHeight()-110),
                             wxTE_MULTILINE | wxTE_AUTO_URL|wxHSCROLL);

    SQLTextBox->SetDefaultStyle(wxTextAttr(*wxBLUE, *wxWHITE, *wxNORMAL_FONT));
    SQLTextBox->SetValue(result);

    dlg.CentreOnScreen();
    if(dlg.ShowModal()==wxID_OK)
     {
    wxString sqltext=SQLTextBox->GetValue();
    if(!sqltext.Trim().IsEmpty())
    {
     sqltext.Replace(wxT("\n"),wxT("<br>"),true);
    wxString SQL =wxT("insert into _notes(term,no,notes)values('")+currentOrder+wxT("',(select ifnull(max(no)+1,1) from _NOTES where term='")+currentOrder+wxT("'),'")+sqltext+wxT("')");
    wxLogMessage(SQL);
        db->executeCRUD(SQL.ToUTF8());
    }

     }
    dlg.Destroy();
    delete db;
BFrame->saveForecastLight=false;
}

//F3 complexAI
void complexAI()
{
  if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
if(BFrame->findBuddyLight)return;//防止多次弹出

BFrame->findBuddyLight=true;


    wxDialog* dlg=
    new wxDialog(NULL, wxID_ANY, wxT("综合分析区"),
                 wxPoint(1,1), wxSize(BFrame->GetSize().GetWidth()-100,
                                           BFrame->GetSize().GetHeight()-150),wxSYSTEM_MENU | \
             wxMINIMIZE_BOX | \
             wxCLOSE_BOX | \
             wxCAPTION | \
             wxCLIP_CHILDREN);

   wxPanel* bgpanel=new wxPanel(dlg, wxID_ANY, wxDefaultPosition, wxSize(dlg->GetSize().GetWidth(),dlg->GetSize().GetHeight()), wxTAB_TRAVERSAL|wxWANTS_CHARS, wxT("COMPLEXAI"));
wxString choices[3] ={wxT("test1"),
                      wxT("test2"),
                      wxT("test3")};
int select = -1;
/*
wxArrayString names;
names.Add(wxT("历史同期记录"));
names.Add(wxT("历史同星期记录"));
names.Add(wxT("个位数字统计"));
wxMultiChoiceDialog* msg =new wxMultiChoiceDialog(NULL,wxT("选项列表"),wxT("选择统计策略"),names,wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxOK ,wxDefaultPosition);
wxArrayInt yourchoices;//choices

if(msg)
{
 select = msg->ShowModal();
  yourchoices=msg->GetSelections();
  if(select == wxID_OK)
  {
   msg->EndModal(select);
  }
 delete  msg;
}
*/

    wxHtmlWindow * html = new wxHtmlWindow(bgpanel,ID_OPEN_HTMLDLG, wxPoint(5,5), wxSize(dlg->GetSize().GetWidth()-15,dlg->GetSize().GetHeight()-75), wxTAB_TRAVERSAL|wxWANTS_CHARS|wxHW_SCROLLBAR_AUTO, wxT("COMPLEXAI"));
//get grid select row red ball
   // wxWebView * html =  wxWebView::New(bgpanel,ID_OPEN_HTMLDLG, "",wxPoint(5,5), wxSize(dlg->GetSize().GetWidth()-15,dlg->GetSize().GetHeight()-75));
 wxFileSystem::AddHandler(new wxMemoryFSHandler());
//wxWebView * html = wxWebView::New(bgpanel, wxID_ANY, "",wxPoint(5,5), wxSize(dlg->GetSize().GetWidth()-15,dlg->GetSize().GetHeight()-75));
   html->Connect(html->GetId(), wxEVT_COMMAND_WEB_VIEW_ERROR,wxWebViewEventHandler(bonusFrame::OnError));
//    html->SetBackgroundColour(*wxGREEN);

wxArrayString result0 =getSelectedGridRowRedBall(BFrame->Grid1,0);//当前行
wxArrayString result_1=getSelectedGridRowRedBall(BFrame->Grid1,-1);//上一期
wxArrayString result_2=getSelectedGridRowRedBall(BFrame->Grid1,-2);
wxArrayString result_3=getSelectedGridRowRedBall(BFrame->Grid1,-3);
wxArrayString result_4=getSelectedGridRowRedBall(BFrame->Grid1,-4);

//find surround
redBallHashMap result=findLUOSHU36SurroundMatrix(result_1);//要根据上一期来做预测

 wxString ls9=wxEmptyString;//formatLUOSHU9(NULL);
 wxString ls16=wxEmptyString;//formatLUOSHU16(NULL);
 wxString ls36=formatLUOSHU36WithSurround(result0,result,false);
wxString cterm =getSelectedGridRowTerm(BFrame->Grid1);
wxString notesSQL=wxT("SELECT term,notes,createdate FROM _NOTES where term='")+cterm+wxT("'");
DoubleBall* db=new DoubleBall();
db->query(notesSQL.char_str());


wxString compare=wxEmptyString;//比较最近三期
compare=compare+wxT("<br><table border=1><thead><th>3</th><th>2</th><th>1</th></thead>")
                +wxT("<tr><td>")+formatLUOSHU36(result_3,result_4,false)+wxT("</td>")
               +wxT("<td>")+formatLUOSHU36(result_2,result_3,false)+wxT("</td>")
               +wxT("<td >")+formatLUOSHU36(result_1,result_2,false)+wxT("</td>")
               +wxT("<td >")+formatLUOSHU36(result0,result_1,false)+wxT("</td>")
               //+wxT("<td >")+ls36+wxT("</td>")
               +wxT("</tr></table>");
 wxString htmlbody=wxEmptyString;

wxArrayString killrb=killLUOSHU36SurroundMatrix(result);

float per=0.0;
int count=0;
if(result0.GetCount()!=0)count=forecastMatch(result,result0,true);
per=(float)count/(float)result0.GetCount();

wxArrayString forecast;
  redBallHashMap::iterator it;
    for( it = result.begin(); it !=result.end(); ++it )
    {
       forecast.Add(it->first);
    }
    forecast.Sort(false);
wxArrayString miss;
miss=forecastMatchMiss(result,result0);
switchHashMap distance=getRedballDistance(result_1);
switchHashMap sum=getRedballSum(result_1);
  htmlbody=htmlbody+wxT("<html>")
          +wxT("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>")
          +wxT("<body bgcolor=#c0c0c0>")
          +wxT("<table border=1>")
          +wxT("<tr><td><font color=BLUE><b>上一期数据:</font><font color=red>")+arrary2string(result_1)+wxT("/</font><font color=blue>本期数据:</font><font color=red>")+arrary2string(result0)+wxT("</font></td></tr>")
//          +formatArraytoHTML(result0)+wxT("</td></tr>")
          +wxT("<tr><td>Notes:")
          +ls9+ls16+compare+wxT("</td></tr>")
          +wxT("<tr><td>")
          +formatNotestoHTML(db)+wxT("</td></tr>");
//          +wxString::Format(wxT("<tr><td>预测数据:%2d,命中%02d,命中率%02.2f%%"),forecast.GetCount(),count,per*100)
//          +formatArraytoHTML(forecast)+wxT("</td></tr>")
//          +wxString::Format(wxT("<tr><td>错漏数据:%2d"),miss.GetCount())
//          +formatArraytoHTML(miss)+wxT("<br> 被杀掉的号码:")+formatArraytoHTML(killrb)+wxT("</td></tr>")

//          +wxT("<tr><td>间距差<br>")+hashmap2html(distance)+wxT("</td></tr>")
//          +wxT("<tr><td>间距和<br>")+hashmap2html(sum)+wxT("</td></tr>")
//          +wxT("<tr><td>都包含数字:")+bothInclude(distance,sum)+wxT("</td></tr>");
//db->query((wxT("select * from _dbhistory where term=")+cterm).char_str());
Statistics* analyst;
//analyst=statisticsRecords(db);
//      htmlbody=htmlbody+wxT("<TR><td>")
//                        +wxT("<table border=1>")
//                       +wxT("<tr><td colspan=4>分区号码</td></tr>")
//                       +wxT("<tr><td><font color=red>01-09</font></td><td><font color=red>10-19</font></td>")
//                       +wxT("<td><font color=red>20-29</font></td><td><font color=red>30-33</font></td></tr>")
//                       +wxT("<tr>")
//                       +wxT("<td>")+arrary2string(analyst->Section01_09)+wxT("</td>")
//                       +wxT("<td>")+arrary2string(analyst->Section10_19)+wxT("</td>")
//                       +wxT("<td>")+arrary2string(analyst->Section20_29)+wxT("</td>")
//                       +wxT("<td>")+arrary2string(analyst->Section30_33)+wxT("</td>")
//                       +wxT("</tr></table>")
//                       +wxT("</td></tr>")  ;


//得到历史上的这一期
wxString term=getSelectedGridRowTerm(BFrame->Grid1);
//wxString historyterm;
wxString historyterm=wxT("select * from _dbhistory where substr(term,5,3)='"+term.Right(3)+wxT("'"));
db->query(historyterm.char_str());
htmlbody=htmlbody
+wxT("<tr><td><font color=blue><b>历史上的同期记录</b></font></td></tr>")
+wxT("<tr><td>")
 +formatDBtoHTML(db,false)
 +wxT("</tr></td>");
analyst=statisticsRecords(db);
htmlbody=htmlbody+wxT("<tr><td colspan=35 width=100%><br><font color=green><b>各个数字出现频率统计:</b></font>")
+wxT("<br><font color=red>红球出现频率统计:</font>")+arrary2string(&analyst->numberCount[0],MAXREDBALL)
+wxT("<br><b><font color=blue>篮球出现频率统计:</font></b>")+arrary2string(&analyst->numberBlueCount[0],MAXBLUEBALL)
+wxT("<br><font color=green><b>红球最大位置出现频率统计:</b></font>")
+arrary2string(&analyst->numberMaxCount[0],MAXREDBALL)+wxT("<br><font color=green><b>红球最小位置出现频率统计:</b></font>")
+arrary2string(&analyst->numberMinCount[0],MAXREDBALL)+wxT("<br>")
+wxT("</td></tr>");
//************************* 分析选项 得到SQL **************************
//yourchoices;//choices
//得到比较个位数
wxString sumChoices=wxEmptyString;

//if(yourchoices.Count()==0 || yourchoices.Index(2)!=wxNOT_FOUND)
//{
/*
        term=getSelectedGridRowTerm(BFrame->Grid1,-1);
        historyterm=wxT("select * from _dbhistory where term='"+term+wxT("'"));
        db->query(historyterm.char_str());
        wxString singles=DB2SingleCollect(db);
        wxString partcon=wxEmptyString;
        historyterm=wxT("select * from _dbhistory where rowid in (select rowid+1 as rowid");
                        partcon=wxT(" from _dbhistory where red1%10 in (")+singles+wxT(") ")
        +wxT(" and red2%10 in (")+singles+wxT(")  ")
        +wxT(" and red3%10 in (")+singles+wxT(")  ")
        +wxT(" and red4%10 in (")+singles+wxT(")  ")
        +wxT(" and red5%10 in (")+singles+wxT(")  ")
        +wxT(" and red6%10 in (")+singles+wxT(")  ");
        historyterm=wxT("Select * ")+partcon +wxT(" union ")+
        wxT("select * from _dbhistory where rowid in (select rowid+1 as rowid")+partcon+wxT(")");
        //get max count
        db->query((wxT("select * ")+partcon).char_str());
        int maxCount = db->nrow-1;//skip header lin.
        int start1 = (maxCount>6)?(maxCount*2-6*2+1):0;
        historyterm = historyterm +wxT(" limit ")+wxString::Format(wxT("%d"),start1)+wxT(",12");
        //wxGetTextFromUser(wxEmptyString,wxT("..."),historyterm);
        db->query(historyterm.char_str());
sumChoices =sumChoices +
+wxT("<tr><td><font color=blue><b>")+term+wxT("期个位分布最近6期(个位数分布:")+singles+wxT(")</b></font></td></tr>");

sumChoices = sumChoices + wxT("<tr><td>")
 +formatDBtoHTML(db,false)
 +wxT("</td></tr>");
sumChoices = sumChoices+ wxT("</table>");
*/
//}


//********************** over*******************************
htmlbody=htmlbody+sumChoices;
 //得到下一期的统计
//start1 = (maxCount>6)?(maxCount-6):0;
// historyterm =wxT("select * from _dbhistory where rowid in (select rowid+1")+partcon+wxT(")") +wxT(" limit ")+wxString::Format(wxT("%d"),start1)+wxT(",6");
//db->query(historyterm.char_str());
//analyst=statisticsRecords(db);
//
//htmlbody=htmlbody+wxT("<tr><td colspan=35 width=100%><br><font color=green><b>下一期6期内各个数字出现频率统计:</b></font>")
////+wxT("<br><font color=red>红球出现频率统计:</font>")+arrary2string(&analyst->numberCount[0],MAXREDBALL)
////+wxT("<br><b><font color=blue>篮球出现频率统计:</font></b>")+arrary2string(&analyst->numberBlueCount[0],MAXBLUEBALL)
//+wxT("</td></tr>");


//得到最近未出红球的间距
//cterm =getSelectedGridRowTerm(BFrame->Grid1,-1);
//if(BFrame->Grid1->GetCursorRow()+1 == BFrame->Grid1->GetNumberRows())
//{
// cterm=wxEmptyString;
//}
//
//htmlbody=htmlbody+wxT("<tr><td colspan=35 width=100%><br><font color=green><b>各个数字间隔距离统计:下一期(")+arrary2string(result0)+wxT(")</b></font>")
//+getMissDistance(cterm)
//+wxT("</td></tr>");
//     htmlbody=htmlbody+wxT("</table>");
/*
cterm =getSelectedGridRowTerm(BFrame->Grid1,-1);
htmlbody=htmlbody+wxT("<tr><td><table border=2><tr><td>")+getDigitsTrendAnalyst(cterm,-5)+wxT("</td></tr></table>");
*/
//得到最近5期篮球和未出红球的关系。
wxString sqls=wxT("select * from _dbhistory where term<='");
wxString sqls1=wxT("select * from _dbhistory where term<'");

wxString sqlt=wxT("' order by term desc limit 6");
wxString sqlt1=wxT("' order by term desc limit 5");

wxString finalsql=wxEmptyString;
wxString missredball;
wxString pblue=wxEmptyString;
for(int i=1;i<33;i++)
{
 term=getSelectedGridRowTerm(BFrame->Grid1,-1*i);
 cterm=getSelectedGridRowTerm(BFrame->Grid1,-1*(i-1));
 pblue=getSelectedGridRowBlueBall(BFrame->Grid1,-1*(i-1));
 finalsql=sqls+term+sqlt;
db->query(finalsql.char_str());
analyst=statisticsRecords(db);
missredball=missredball
   +wxT("<tr><td>")+cterm+wxT("</td><td><font color=red><bold>")+arrary2string(analyst->getMissRedsLimitBlue())+wxT("</bold></font></td>");
//2.
 finalsql=sqls1+term+sqlt1;
db->query(finalsql.char_str());
analyst=statisticsRecords(db);
missredball=missredball+wxT("<td><font color=red><bold>")+arrary2string(analyst->getMissRedsLimitBlue())+wxT("</bold></font></td><td><font color=blue><bold>")+pblue+wxT("</bold></font></td></tr>");
}
missredball=wxT("<tr></td><table border=1>")+missredball+wxT("</table>");
     htmlbody=htmlbody+missredball
       +wxT("</td></tr></table>")
       +wxT("</body></html>");

 //wxGetTextFromUser(wxEmptyString,wxEmptyString,htmlbody);//get real html source code

//        wxMemoryFSHandler::AddFile("data.html",
//                                "<html><body><h1>Hello,World</h1></body></html>");
    html->SetPage(htmlbody);

    wxButton* ok = new wxButton(bgpanel,wxID_OK,wxT("确定"),wxPoint(bgpanel->GetSize().GetWidth()/2-50,bgpanel->GetSize().GetHeight()-60));
    wxButton*  copy = new wxButton(bgpanel,ID_BUTTON_COPYCLIPBOARD,wxT("复制到剪贴板"),wxPoint(bgpanel->GetSize().GetWidth()/2+50,bgpanel->GetSize().GetHeight()-60));
    wxButton *print  = new wxButton(bgpanel,ID_BUTTON_PRINT_PAGE, wxT("打印..."),wxPoint(bgpanel->GetSize().GetWidth()/2+150,bgpanel->GetSize().GetHeight()-60));

    BFrame->_CLIPBOARD=htmlbody;//for clipboard
    GlobalEvtHandler::CurrentPAGE=htmlbody;//for print
    copy->Connect(wxEVT_LEFT_DOWN,wxCommandEventHandler(bonusFrame::OnCopytoClipBoard));
    print->Connect(wxEVT_LEFT_DOWN,wxCommandEventHandler(GlobalEvtHandler::OnPagePrintHandler));

      dlg->CentreOnScreen();
 dlg->Show();
   // wxMemoryFSHandler::RemoveFile("data.htm");

delete db;
//delete analyst;
BFrame->findBuddyLight=false;//防止多次弹出
}

//F4 弹出篮球,包括两个方向
void openBlueBallWindow(bool hozi)
{
wxString SQL=wxT("select term,blue from _DBHISTORY  order by term asc");

DoubleBall * db=new DoubleBall();
db->query(SQL.char_str());

    wxDialog* dlg=
    new wxDialog(NULL, wxID_ANY, wxT("篮球"),
                 wxPoint(1,1), wxSize(BFrame->GetSize().GetWidth()-100,
                                           BFrame->GetSize().GetHeight()-150),wxSYSTEM_MENU | \
             wxMINIMIZE_BOX | \
             wxCLOSE_BOX | \
             wxCAPTION | \
             wxCLIP_CHILDREN);
//wxPanel* hpanel=new wxPanel(dlg, wxID_ANY, wxDefaultPosition, wxSize(BFrame->GetSize().GetWidth()-100,
//                                           BFrame->GetSize().GetHeight()-150),
//                             wxTAB_TRAVERSAL|wxWANTS_CHARS|wxBORDER_DOUBLE , wxT(""));

 wxBoxSizer *vboxPnl = new wxBoxSizer(wxVERTICAL);
 wxSizer* sizer=dlg->CreateButtonSizer(wxOK|wxCANCEL);

   wxFont* gFont= new wxFont(10, wxDEFAULT, wxNORMAL, wxFONTWEIGHT_BOLD, 0, wxT("Sans"));

  wxGrid* bluegrid = new wxGrid(dlg, wxNewId(), wxPoint(10,10), wxSize(dlg->GetSize().GetWidth()-10, dlg->GetSize().GetHeight()-10), wxWANTS_CHARS, wxT("BLUE Grid"));

  bluegrid->SetDefaultCellFont(*gFont);
    bluegrid->SetEditable(false);

if(hozi)
  {
  bluegrid->SetDefaultRenderer(new BlueBallRenderer(true));
  bluegrid->CreateGrid(16,db->nrow,wxGrid::wxGridSelectColumns);
  }else
  {
   bluegrid->SetDefaultRenderer(new BlueBallRenderer(false));
   bluegrid->CreateGrid(db->nrow,16,wxGrid::wxGridSelectColumns);
  }

//set row label
int row_col_widht=24;
if(hozi)
{
    for (int i=0;i<16;i++)
      {
          bluegrid->SetRowLabelValue(i,wxString::Format(wxT("%02d"),16-i));
          bluegrid->SetRowMinimalHeight(i,row_col_widht);
      }
}else
{
    for (int i=1;i<=db->nrow;i++)
      {
          bluegrid->SetRowLabelValue(i-1,wxString::FromAscii(db->records[i*db->ncol]));
          bluegrid->SetRowHeight(i-1,row_col_widht);
     wxString   bluevalue=wxString::Format(wxT("%02d"),atoi(db->records[i*db->ncol+1]));
     int value=atoi(db->records[i*db->ncol+1])-1;

     bluegrid->SetCellValue(i-1,value,bluevalue);
     bluegrid->SetCellTextColour(i-1,value,*wxBLUE);
     if(value+1<=8)
     bluegrid->SetCellBackgroundColour(i-1,value,*wxCYAN);
      }

}

//set column label
wxString term=wxEmptyString;
wxString bluevalue=wxEmptyString;
if(hozi)
{
for(int i=1;i<=db->nrow;i++)
  {
   term=wxString::Format(wxT("%d"),atoi(db->records[i*db->ncol]));
   bluevalue=wxString::Format(wxT("%02d"),atoi(db->records[i*db->ncol+1]));

   bluegrid->SetColLabelValue(i-1,term);
   bluegrid->SetCellValue(16-atoi(db->records[i*db->ncol+1]),i-1,bluevalue);
  }

bluegrid->MakeCellVisible(15,db->nrow-1);

}else
{
for(int i=1;i<=16;i++)
  {

   bluegrid->SetColLabelValue(i-1,wxString::Format(wxT("%02d"),i));
   bluegrid->SetColumnWidth(i-1,row_col_widht);
  }

bluegrid->MakeCellVisible(bluegrid->GetNumberRows()-1,0);
}
// hpanel->Add(bluegrid, 0, wxALL|wxEXPAND, 10);



//wxButton *btnOk = new wxButton(dlg, wxID_CANCEL, wxT("&Ok"));
//GlobalEvtHandler::h_dialog = dlg;
//btnOk->Connect(wxEVT_LEFT_DOWN,wxCommandEventHandler(GlobalEvtHandler::DestroyDialog));

  vboxPnl->Add(bluegrid, 0, wxALL|wxEXPAND, 10);
 vboxPnl->Add(sizer, 1, wxCENTRE);

 bluegrid->ForceRefresh();
  dlg->SetSizer(vboxPnl);
vboxPnl->SetSizeHints(dlg);
     vboxPnl->Fit(dlg);

 dlg->Show();
// int code=dlg.ShowModal();
//  dlg.EndModal(code);
 delete db;
}
//F5输入窗口风格列数
void changeDivideCol()
{
      if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
long value=DoubleBallGridCellRenderer::DIVIDE_COL;
value=wxGetNumberFromUser(wxT("输入列分割数目:"),
wxT("选择数字:"),wxT("列分割数目选择框"),value,1,33,NULL,wxDefaultPosition);

if(value!=-1)
DoubleBallGridCellRenderer::DIVIDE_COL=value;
BFrame->Grid1->ForceRefresh();

}
//F7 根据一些模式开始预测,

void patternFinder()
{
       if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
if(BFrame->findBuddyLight)return;//防止多次弹出

BFrame->findBuddyLight=true;
 //得到当前行的所有红球数量.
 wxArrayString redballs=getSelectedGridRowRedBall(BFrame->Grid1);

 wxString curTerm=getSelectedGridRowTerm(BFrame->Grid1);
 int count=0;//看有几个红球
 int left=0;//差几个红球
 count=redballs.GetCount();
 left=MAXREDBALL-count;
 if(left<=0)left=0;
 string* others=new string[left];//剩余红球

 int index=0;
 wxString test;
   for(int k=1;k<=MAXREDBALL;k++)
   {
      wxString value=wxString::Format(wxT("%02d"),k);
     if(redballs.Index(value.c_str())== wxNOT_FOUND )
     {
       others[index]=value.mb_str();
       test=test+wxT(",")+value;
       index++;
     }
   }
//wxMessageBox(test+wxString::Format(wxT("left:%02d-(6-count)%02d"),left,6-count));
 if(redballs.GetCount()==0)
 {
   wxMessageBox(wxT("空行,没必要!考虑加入手选评估!"));
   BFrame->findBuddyLight=false;
   return;
 }
 //ask match >=4 redball 多少纪录
 long lines=::wxGetNumberFromUser(wxT("输入历史纪录匹配的个数"),wxT("请输入匹配记录个数:"),wxT("标题"),4,0,20);
 if(lines==-1){BFrame->findBuddyLight=false;return;}//cancle button
    //initial
 string allcombin=combine(others,left,6-count);
 wxLogMessage(wxT("数据是:%s"),allcombin.c_str());
wxArrayString allcombinarray=split(wxString(allcombin.c_str(), wxConvUTF8));
//wxMessageBox(arrary2string(allcombinarray));

     DoubleBall* db =new DoubleBall();
     char * SQL="select * from _dbhistory";
    db->query(SQL);

    wxArrayString matchRecords4;//符合匹配的记录term号
    wxArrayString matchRecords5;//符合匹配的记录term号
    wxArrayString matchRecords;//符合匹配的记录term号

    wxString value=wxEmptyString;

    count=0;//匹配个数指示
    long num;
    wxString term=wxEmptyString;
    wxString result;
    wxString app;//
    wxArrayString tmpArray;
   for(int k=0;k<allcombinarray.GetCount();k++)
    {
     tmpArray.clear();
     wxString eachArray=allcombinarray.Item(k);
    wxStringTokenizer data(eachArray,wxT(","));
    while ( data.HasMoreTokens() )
     {
      tmpArray.Add(data.GetNextToken());
     }
      if(redballs.Index(value.c_str())!= wxNOT_FOUND )continue;//skip this

     for(int i=1;i<=db->nrow;i++) //first limatchRecordsne is col lable
        {
        term=wxString(db->records[i*db->ncol],wxConvUTF8);//0 is term key

        for(int j=2;j<db->ncol-1;j++) //第一列是term,2是日期要跳过,最后两个是blue
        {
          value = wxString::Format(wxT("%02d"),atoi(db->records[i*db->ncol+j]));
          if(redballs.Index(value.c_str())!= wxNOT_FOUND )//find it
          {
           count++;
          }else //not find
          {
          if(tmpArray.Index(value.c_str())!= wxNOT_FOUND )count++;
          }
        }

        if(count==4 ){matchRecords4.Add(term);}
        if(count==5 && (term!=curTerm)){matchRecords5.Add(term);}
        count=0;//reset
        term=wxEmptyString;
        }
         wxString tmp=arrary2string(redballs)+wxT(",")+arrary2string(tmpArray);
        if(matchRecords4.GetCount()==lines||matchRecords5.GetCount()==lines)
        {
//        if(matchRecords.Index(tmp.c_str()==wxNOT_FOUND))matchRecords.Add(tmp);
        result=result+wxT("<tr><td>")+tmp+wxT("</td></tr>");
        }
        matchRecords4.Clear();
        matchRecords5.Clear();
//if(redballs.GetCount()>=6)break;//skip ,just once check.

    }

    //for sql
delete others;
delete db;
showHTMLMessage(wxT("<table border=1>")+(result)+wxT("</table>"));
BFrame->findBuddyLight=false;
}

//Ctrl+G,调到指定期
void skipTerm()
{
  if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
//    long value;
//value = ::wxGetNumberFromUser(wxT("输入划分的列"),wxT("输入数字列"),wxT("要输入划分的列"),7,7,16,NULL,wxDefaultPosition);
wxString term=::wxGetTextFromUser(wxT("输入期号"),wxT("输入跳转的旗号"),wxEmptyString,NULL,wxDefaultCoord,wxDefaultCoord,true);
if(term==wxEmptyString)return;
if(locateByTerm(term))return;
 wxMessageBox(wxT("没有发现制定的期号:")+term);
}

//工具类，实现通用跳转
bool locateByTerm(wxString term)
{
 bool success=false;
   int x, y,x2,y2;
  BFrame->Grid1->CalcUnscrolledPosition(0, 0, &x, &y);
int startrow=BFrame->Grid1->YToRow(y);
 if(!BFrame->Grid1->IsVisible(startrow,0))startrow=startrow+1;
   BFrame->Grid1->GetVirtualSize(&x2,&y2);
int endrow=BFrame->Grid1->YToRow(y2);
  if(!BFrame->Grid1->IsVisible(endrow,0))endrow=endrow-1;

for(int i=0;i<BFrame->Grid1->GetNumberRows();i++)
{
  if(BFrame->Grid1->GetCellValue(i,0)==term)
   {
       success=true;
    BFrame->Grid1->SelectBlock(i,0,i,BFrame->Grid1->GetNumberCols()-1,true);
    if(i>=endrow )
    {
        if(i<=BFrame->Grid1->GetNumberRows()-10)
        {i=i+10;}
        else{i=BFrame->Grid1->GetNumberRows()-1;}
    }
    if(i<=startrow)
    {
        if(i>=20)
        {i=i-20;}
        else
        {
          i=0;
        }
    }

    BFrame->Grid1->MakeCellVisible(i,0);
    break;
      }
}
return success;
}
//Ctrl+P 打印Grikd
void printGrid()
{
  if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
int pagerows=30;//一页的行数

if(BFrame->findBuddyLight)return;//防止多次弹出
BFrame->findBuddyLight=true;//防止多次弹出
 GlobalEvtHandler* geh=new GlobalEvtHandler();
  int x, y,x2,y2;
  BFrame->Grid1->CalcUnscrolledPosition(0, 0, &x, &y);
int startrow=BFrame->Grid1->YToRow(y);
if(!BFrame->Grid1->IsVisible(startrow,0))startrow=startrow+1;
BFrame->Grid1->GetVirtualSize(&x2,&y2);

int rows=BFrame->Grid1->YToRow(y2);
wxString willstart=::wxGetTextFromUser(wxT("输入打印起始期:"),wxEmptyString,BFrame->Grid1->GetTable()->GetValue(startrow,0));
if(willstart!=wxEmptyString)
{
 int row=  getGridRowLine(willstart);
 if(row!=-1)startrow=row;
}

//wxMessageBox(wxString::Format(wxT("%02d,%02d,")+BFrame->Grid1->GetCellValue(startrow,0),startrow,rows));
wxString page=formatGridtoHTML(BFrame->Grid1,startrow,rows,pagerows);
 wxCommandEvent a;
 geh->CurrentPAGE=page;
 geh->OnPagePrintHandler(a);
 page=wxEmptyString;
BFrame->findBuddyLight=false;//防止多次弹出
}
//Ctrl+V 粘贴数据到当前行
void pasteToGrid(wxKeyEvent& ev)
{
  wxString redball;
  if(BFrame->Grid1==NULL)
  {
     wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
  int row=BFrame->Grid1->GetCursorRow();

   if(row==0)row=BFrame->Grid1->GetNumberRows()-1;

  if (wxTheClipboard->Open())
  {
      wxTextDataObject data;
    wxTheClipboard->GetData(data);
    redball=data.GetText();
    wxTheClipboard->Close();
  }

if(redball.length()<1)return;

wxStringTokenizer  rb(redball,wxT(",-: \t"),wxTOKEN_RET_EMPTY_ALL);
long col=0;
while ( rb.HasMoreTokens() )
{
    wxString token = rb.GetNextToken();
    if(token.IsNumber()) token.ToLong(&col,10);
    if(col>33)//应该是期号
    {
    BFrame->Grid1->SetCellValue(row,0,token);
    }else
    {
    BFrame->Grid1->SetCellValue(row,col+1,token);
    }
}
}
//F6 查找同当前期具有5个相似的号码
void findBuddy()
{
      if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
if(BFrame->findBuddyLight)return;//防止多次弹出

BFrame->findBuddyLight=true;

//得到当前行的所有红球数量.
 wxArrayString redballs=getSelectedGridRowRedBall(BFrame->Grid1);
 if(redballs.GetCount()==0)
 {
   wxMessageBox(wxT("空行,没必要!考虑加入手选评估!"));
   BFrame->findBuddyLight=false;
   return;
 }
//wizard

redballDialog* rbd=new redballDialog(NULL);
rbd->parseString(redballs);
 //set default AIsql

 wxString result=wxEmptyString;
 long vl1,vl2;

 for(int i=0;i<redballs.GetCount()-1;i++)
 {
  if(i<(redballs.GetCount()-1))
  {
    redballs[i].ToLong(&vl1,10);
    redballs[i+1].ToLong(&vl2,10);
   if((vl2-vl1)==1 or (vl2-vl1)==2)
   {

     result = result +(result==wxEmptyString?wxT(""):wxT(" and "))+ wxT(" (red")+wxString::Format(wxT("%d"),i+2)+wxT("-red")+wxString::Format(wxT("%d"),i+1)+wxT("=")+wxString::Format(wxT("%d"),(vl2-vl1))+wxT(") ");
   }
   }
  }
//rbd->balltext->Clear();
//rbd->balltext->SetInsertionPoint(0);
 rbd->balltext->SetValue(result);
 if(rbd->ShowModal()==wxID_OK)
  {
   redballs=rbd->selectedredball;
   rbd->EndModal(wxID_OK);
  }else
  {
   BFrame->findBuddyLight=false;

   return;
  }


 wxString AIsql = rbd->balltext->GetValue();

 wxString curTerm=getSelectedGridRowTerm(BFrame->Grid1);



    wxDialog dlg;
    dlg.Create(BFrame, wxID_ANY, wxT("统计相似个数"),
                 wxDefaultPosition, wxSize(BFrame->GetSize().GetWidth()-100, BFrame->GetSize().GetHeight()-200));


   wxPanel* bgpanel=new wxPanel(&dlg, wxID_ANY, wxDefaultPosition, wxSize(dlg.GetSize().GetWidth(),dlg.GetSize().GetHeight()), wxTAB_TRAVERSAL|wxWANTS_CHARS, wxT("saveforcast"));

    wxHtmlWindow * html = new wxHtmlWindow(bgpanel,ID_OPEN_HTMLDLG, wxPoint(10,10), wxSize(dlg.GetSize().GetWidth()-20,450), wxHW_SCROLLBAR_AUTO|wxBORDER_DOUBLE |wxWANTS_CHARS );
    html->   Connect(ID_OPEN_HTMLDLG,wxEVT_COMMAND_HTML_LINK_CLICKED,wxHtmlLinkEventHandler(bonusFrame::OnHtmlLinkClicked));
    html->SetBackgroundColour(*wxGREEN);
    //initial
     DoubleBall* db =new DoubleBall();
     char * SQL="select * from _dbhistory";
    db->query(SQL);
    wxArrayString matchRecords4;//符合匹配的记录term号
    wxArrayString matchRecords5;//符合匹配的记录term号
    wxString value=wxEmptyString;

    int count=0;//匹配个数指示
    wxString term=wxEmptyString;
     for(int i=1;i<=db->nrow;i++) //first line is col lable
        {
        term=wxString(db->records[i*db->ncol],wxConvUTF8);//0 is term key
        for(int j=2;j<db->ncol-1;j++) //第一列是term,2是日期要跳过,最后两个是blue
        {
          value = wxString::Format(wxT("%02d"),atoi(db->records[i*db->ncol+j]));

          if(redballs.Index(value.c_str())!= wxNOT_FOUND )count++;
        }
 //       wxLogMessage(term+wxT(" has  %02d"),count);
    //    wxLogMessage(term+wxT("  %02d"),count);
        if(count==4)matchRecords4.Add(term);
        if(count>=5 && term!=curTerm)matchRecords5.Add(term);
        count=0;//reset
        term=wxEmptyString;
        }        if(count>=5 && term!=curTerm)matchRecords5.Add(term);

    //for sql
    wxString Where=wxEmptyString;
//符合4次 DoubleBall* db =new DoubleBall();
    if(matchRecords4.GetCount()>0)
    {
     for(int t=0;t<matchRecords4.GetCount();t++)
      {
        Where=Where+matchRecords4[t];
        if(t<matchRecords4.GetCount()-1)Where=Where+wxT(",");
      }

    }
    wxString finalSQL=wxT("select * from _dbhistory where term in(")+Where+wxT(")");
    wxLogMessage(finalSQL);
    db->query(finalSQL.char_str());
    wxString result4= formatDBtoHTML(db);

//符合5次
     Where=wxEmptyString;
    if(matchRecords5.GetCount()>0)
    {
     for(int t=0;t<matchRecords5.GetCount();t++)
      {
        Where=Where+matchRecords5[t];
        if(t<matchRecords5.GetCount()-1)Where=Where+wxT(",");
      }

    }
    wxString finalSQL5=wxT("select * from _dbhistory where term in(")+Where+wxT(")");
    wxLogMessage(finalSQL5);
    db->query(finalSQL5.char_str());
    wxString result5= formatDBtoHTML(db);
    //add 2011.1.12 add mate find
   wxString numbermate = formatNumberMate(curTerm);
//format to html page
  wxString HTML =wxT("<table border=1 valign=top><thead><th>4个数字</th><th>5个数字</th></thead>");
  //desc
  HTML=HTML+wxT("<tr><td colspan=2>当前期:<font color=red size=+2>")+curTerm+wxT("</font>:")+arrary2string(redballs)+wxT("</td></tr>");
 //red count
   HTML=HTML+wxT("<tr><td align=center> 记录数:")+wxString::Format(wxT("%02d"),matchRecords4.GetCount())+wxT("</td>");
   HTML=HTML+wxT("<td align=center> 记录数:")+wxString::Format(wxT("%02d"),matchRecords5.GetCount())+wxT("</td></tr>");
   HTML=HTML+wxT("<tr vlign=top><td>")+result4+wxT("</td>")+wxT("<td valign=top>")+result5+wxT("</td></tr>");;
   //add 2010.1.12
   HTML=HTML+wxT("<tr><td>本期的mate: " )+numbermate+wxT(" </td>")+wxT("<td>")+wxT("</td></tr>");;
   HTML=HTML+wxT("</table>");

   //add by 2011.2.07 for AI string
   if(AIsql!= wxEmptyString )
   {
   wxString guessSQL = wxT("select rowid+1 from _dbhistory where ")+AIsql;
   guessSQL = wxT("select * from _dbhistory where rowid in (")+guessSQL+wxT(")")
            + wxT(" union select * from _dbhistory where ")+AIsql;
    wxLogMessage(guessSQL);

Statistics* analyst;
db->query(guessSQL.char_str());
analyst=statisticsRecords(db);
HTML=HTML+wxT("<table border=1>")
    +wxT("<tr><td colspan=35><br><font color=green><b>条件:")+AIsql+wxT("</b></font></td></tr>")
    +wxT("<tr><td colspan=35>")+formatDBtoHTML(db)+wxT("</td></tr>")
    +wxT("<tr><td colspan=35 ><br><font color=green><b>各个数字出现频率统计:</b></font>")
    +wxT("<br><font color=red>红球出现频率统计:</font>")+arrary2string(&analyst->numberCount[0],MAXREDBALL)
    +wxT("<br><b><font color=blue>篮球出现频率统计:</font></b>")+arrary2string(&analyst->numberBlueCount[0],MAXBLUEBALL)
    +wxT("<br><font color=green><b>红球最大位置出现频率统计:</b></font>")
    +arrary2string(&analyst->numberMaxCount[0],MAXREDBALL)+wxT("<br><font color=green><b>红球最小位置出现频率统计:</b></font>")
    +arrary2string(&analyst->numberMinCount[0],MAXREDBALL)+wxT("<br>")
    +wxT("</td></tr>")
    +wxT("</table>");
   }

      html->SetPage(HTML);
   //add by 2011.1.13
   GlobalEvtHandler::CurrentPAGE=HTML;//for print
   BFrame->_CLIPBOARD=HTML;
    wxButton* ok = new wxButton(bgpanel,wxID_OK,wxT("确定"),wxPoint(bgpanel->GetSize().GetWidth()/2-80,bgpanel->GetSize().GetHeight()-60));
    //add by 2011.1.13
    wxButton* print = new wxButton(bgpanel,wxID_OK,wxT("打印"),wxPoint(bgpanel->GetSize().GetWidth()/2+50,bgpanel->GetSize().GetHeight()-60));
    print->Connect(wxEVT_LEFT_DOWN,wxCommandEventHandler(GlobalEvtHandler::OnPagePrintHandler));
    dlg.CentreOnScreen();
    if(dlg.ShowModal()==wxID_OK)
     {
     dlg.EndModal(wxID_OK);
     }
   dlg.Destroy();

    delete rbd;
    delete db;

BFrame->findBuddyLight=false;//防止多次弹出

}

/*
F8测试代码
*/
void  Incantation()
{

wxDialog dlg(NULL, wxID_ANY, wxT("HTML 窗口"),
                 wxDefaultPosition, wxSize(wxGetDisplaySize().GetWidth()*0.8, wxGetDisplaySize().GetHeight()*0.8));

        wxBoxSizer *vboxPnl = new wxBoxSizer(wxVERTICAL);


    wxHtmlWindow * html = new wxHtmlWindow(&dlg,ID_OPEN_HTMLDLG, wxPoint(10,10), wxSize(dlg.GetSize().GetWidth()-20,dlg.GetSize().GetHeight()-175), wxTAB_TRAVERSAL|wxWANTS_CHARS|wxHW_SCROLLBAR_AUTO, wxT("COMPLEXAI"));
    html->SetBackgroundColour(*wxGREEN);
    wxString result =wxT("Incantation.html");
    html->LoadPage(result);

 vboxPnl->Add(html, 0, wxALL|wxEXPAND, 10);
 wxBoxSizer *hboxPnl = new wxBoxSizer(wxHORIZONTAL );
 wxButton * ok = new wxButton(&dlg, wxID_OK, L"确定");
     GlobalEvtHandler::CurrentPAGE=result;//for print
 hboxPnl->Add(ok, 0, wxCENTRE);
vboxPnl->Add(hboxPnl,0,wxCENTRE);

 dlg.SetSizer(vboxPnl);
    dlg.Layout();
    dlg.Fit();

int code=dlg.ShowModal();
 dlg.EndModal(code);

}
/*
考虑通过 Cantor Diagonal 方法来确定某种趋势
*/
void saveToHTML()
{
      if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
if(BFrame->findBuddyLight)return;//防止多次弹出

BFrame->findBuddyLight=true;
 wxFileDialog saveFileDialog(NULL, _("Save HTML file"), "", "","HTML files (*.HTML)|*.html", wxFD_SAVE|wxFD_OVERWRITE_PROMPT);

if (saveFileDialog.ShowModal() == wxID_CANCEL)
 return; // the user changed idea...
// save the current contents in the file;
// this can be done with e.g. wxWidgets output streams:
//wxFileOutputStream output_stream(saveFileDialog.GetPath());
//wxLogMessage(wxT("File Dir:")+saveFileDialog.GetPath());
//
//if (!output_stream.IsOk())
//{
//wxLogError("Cannot save current contents in file '%s'.", saveFileDialog.GetPath());
//return;
//}
//code body
  wxTextFile text_output(saveFileDialog.GetPath());

DoubleBall* db =new DoubleBall();
     char * SQL="select * from _dbhistory";
    db->query(SQL);

    wxString value=wxEmptyString;

    wxString temp =wxEmptyString;
    wxString result;
    wxString app;//
    wxArrayString tmpArray;
   result =_("")+wxT("<html>\n<body>\n")
     +wxT("<style>.red { font-size: 16; font-weight: bold; color: red }\n")
     +wxT(".blue { font-size: 16; font-weight: bold; color: blue }")
     +wxT("</style>\n")
     +wxT("<table border=1>");
   result=result+wxT("<thead>");
   int tvalue=0;
     result=result+wxT("<td>Term")+wxT("</td>");
     result=result+wxT("<td>Date")+wxT("</td>");
    for(int t=1;t<=33;t++)//make header
    {
    result=result+wxT("<td><font color=red><b>")+wxString::Format(wxT("%02d"),t)+wxT("</b></font></td>");
     }
result=result+wxT("<td><font color=blue><b>Blue</b></font>")+wxT("</td>");

   result=result+wxT("</thead>");
   text_output.AddLine(result);
result=wxEmptyString;
     for(int i=1;i<=db->nrow;i++) //first limatchRecordsne is col lable
        {
        result=result+wxT("<tr class=red>");
          value=wxEmptyString;
          temp=wxEmptyString;

            value=value+wxT("<td>");//term
            temp = wxString(db->records[i*db->ncol],wxConvUTF8);
            value=value+temp+wxT("</td>\n");
            temp = wxString(db->records[i*db->ncol+1],wxConvUTF8);//date
            value=value+wxT("<td>")+temp+wxT("</td>\n");
       for(int t=1;t<=33;t++)//column form 1-36,33 red + term+date+blue
           {
            value=value+wxT("<td>");
            temp=wxEmptyString;
            for(int j=2;j<(db->ncol-1);j++) //第一列(0)是rowid,去掉
           {
               tvalue = atoi(db->records[i*db->ncol+j]);
               if(tvalue == t )
               {
                temp=wxString::Format(wxT("%02d"),tvalue);
                break;//find match skip.
               }
           }
           value=value+temp+wxT("</td>\n");
        }
        //blue ball
        value=value+wxT("<td class=blue>");
        temp = wxString::Format(wxT("%02d"),atoi(db->records[i*db->ncol+(db->ncol-1)]));
        value=value+temp+wxT("</td>\n");

     result=result+value+wxT("</tr>\n");
     text_output.AddLine(result);
     result=wxEmptyString;
    }
    result = _("")+ wxT("</table>\n</body>\n")  + wxT("</html>");
  text_output.AddLine(result);
delete db;
text_output.Write();
text_output.Close();
// wxBufferedOutputStream buf_output( output_stream );

//text_output.WriteString(result);
//text_output<< result <<endl;
//text_output.Flush();
//output_stream.Close();
wxLogMessage(saveFileDialog.GetPath()+wxT(" 输出完成"));
BFrame->findBuddyLight=false;
}

void refreshStastatistics(wxKeyEvent& ev)
{
  wxString redball;
  if(BFrame->Grid1==NULL)
  {
     wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
  int row=BFrame->Grid1->GetCursorRow();

   if(row==0)row=BFrame->Grid1->GetNumberRows()-1;
  wxString curTerm=getSelectedGridRowTerm(BFrame->Grid1);
  wxString lastTerm =getSelectedGridRowTerm(BFrame->Grid1,-1);
  //add 2011.2.07
  wxString blueball = getSelectedGridRowBlueBall(BFrame->Grid1);

//预测当前期的数据，必须排除当前期
wxString notesSQL=wxT("SELECT * FROM _DBHISTORY where term<'")+curTerm+wxT("'  order by rowid desc limit 0,5");


DoubleBall* db=new DoubleBall();

db->query(notesSQL.char_str());
Statistics* analyst=statisticsRecords(db);
wxArrayString historyballs = analyst->getHistoryNumbers();
wxArrayString historymissball;
boolean blueInRedHistory=false;
const wxChar * value;
for(int i=1;i<=MAXREDBALL;i++)
 {
     value=wxString::Format(wxT("%02d"),i).c_str();
   if(historyballs.Index(value)==wxNOT_FOUND)
     {
      historymissball.Add(value);
     }
 }
//绿球是否出现过。
for(int i=1;i<=MAXBLUEBALL;i++)
 {
     value=wxString::Format(wxT("%02d"),i).c_str();
   if(historyballs.Index(blueball)!=wxNOT_FOUND)
     {
      blueInRedHistory=true;
      break;//发现篮球匹配红球跳出
     }
 }
wxString message=wxT("");

wxArrayString curRedBalls = getSelectedGridRowRedBall(BFrame->Grid1,0);
wxArrayString lastRedBalls;
if(lastTerm!=wxEmptyString)
{
   lastRedBalls = getSelectedGridRowRedBall(BFrame->Grid1,-1);
}
message=wxT("本期")+curTerm+wxT(":")+arrary2string(curRedBalls)+wxT("\n<br>最近5期出过的红球:<b><font size=+2>")
    +wxString::Format(wxT("%02d"),historyballs.GetCount())+wxT("</font>个:<font color=red><b>")
    + arrary2string(historyballs)+wxT("</b></font>")
    +(lastRedBalls.GetCount()>0?formatLUOSHU36WithPredict(lastRedBalls,curRedBalls):wxT(""));
   // + statis2string(db,analyst,notesSQL,false);
message=message+wxT("<br>")+formatSection(curRedBalls);
message=message+formatIsolation(curRedBalls);
wxArrayString missball;
wxArrayString matchball;
//得到历史记录遗漏红球
if(historymissball.GetCount()>0)
{
 message= message +wxT("\n<br>最近5期 <u>遗漏</u>红球<font size=+2><b>")+wxString::Format(wxT("%02d"),historymissball.GetCount())+wxT("个</b></font>:\n<b><font color=red>")+arrary2string(historymissball)+wxT("</font></b>");
}
//得到匹配
if(curRedBalls.GetCount()>0)
{
    missball = forecastMatchMiss(historyballs,curRedBalls);
    message = message + wxT("<br>当前期")+curTerm+wxT("记录红球<font color=red><b>")+arrary2string(missball)+wxT("</font>没有出现在最近5期历史记录中!");
}
//得到匹配
if(blueInRedHistory)
{
    message = message + wxT("<br>当前期")+curTerm+wxT("记录绿球<font color=blue size=+3><b><u>")+blueball+wxT("</u></font>出现在红球最近5期历史记录中!");
}else
{
     message = message + wxT("<br>当前期")+curTerm+wxT("记录绿球<font color=blue size=+3><b><u>")+blueball+wxT("</u></font>没有出现在红球最近5期历史记录中!");
}

if(lastRedBalls.Index(blueball)!=wxNOT_FOUND)
{
message = message + wxT("<br>当前篮球")+blueball+wxT("<font size=+3 color=red>出现</font>在上期红球中！！规律！！！");
}else
{
message = message + wxT("<br>当前篮球")+blueball+wxT("<font size=+3 color=red>没有</font>出现在上期红球中!!规律！！！");
}
//ADD 2011.2.08 加入历史同期数据统计

wxString historyterm=wxT("select * from _dbhistory where substr(term,5,3)='"+curTerm.Right(3)+wxT("' and term <> '"+curTerm+wxT("'")));
wxLogMessage(historyterm);

db->query(historyterm.char_str());
//记录

analyst=statisticsRecords(db);
historyballs = analyst->getHistoryNumbers();
historymissball.Clear();
message=message+wxT("\n<br>历史同期出过的<font color=red><b>红球</b></font>:<b><font size=+2>")
+wxString::Format(wxT("%02d"),historyballs.GetCount())+wxT("</b></font>个<br><b><font color=red>")
+ arrary2string(historyballs)+wxT("</b></font>");

message=message+wxT("\n<br>历史同期出过的<font color=blue><b>篮球</b></font>:<b><font size=+2>")
+wxString::Format(wxT("%02d"),analyst->getHistoryBlueNumbers().GetCount())+wxT("</b></font>个<br><b><font color=red>")
+ arrary2string(analyst->getHistoryBlueNumbers())+wxT("</b></font>");
/*
//判断当前数据在历史同期数据中的匹配结果
for(int i=1;i<=MAXREDBALL;i++)
 {
     value=wxString::Format(wxT("%02d"),i).c_str();
   if(historyballs.Index(value)==wxNOT_FOUND)
     {
      historymissball.Add(value);
     }
 }
//得到历史同期记录遗漏红球
if(historymissball.GetCount()>0)
{
 message= message +wxT("<br>历史同期遗漏红球:<b><font size=+2>")
    +wxString::Format(wxT("%02d"),historymissball.GetCount())
    +wxT("</b></font>个 <font size=+2><br><b>")+wxT("</b></font>\n<b><font color=red>")+arrary2string(historymissball)+wxT("</font></b>");
}
//得到匹配
if(curRedBalls.GetCount()>0)
{
    //当前期红球在历史同期出现红球中的匹配
    missball = forecastMatchMiss(historyballs,curRedBalls);
    matchball = forecastMatch(historyballs,curRedBalls);

    if(missball.GetCount()>0)
    message = message + wxT("<br>当前期")+curTerm+wxT("记录红球<font color=red><b>")+arrary2string(missball)+wxT("</font>没有出现在历史同期记录中!");
//    if(matchball.GetCount()>0)
//    message = message + wxT("<br>当前期")+curTerm+wxT("记录红球<font color=red><b>")+arrary2string(matchball)+wxT("</font>出现在历史同期记录中!");

   //当前期红球在历史同期没有出现红球中的匹配
    missball =  forecastMatchMiss(historymissball,curRedBalls);
     matchball = forecastMatch(historymissball,curRedBalls);
    if(missball.GetCount()>0)
    message = message + wxT("<br>当前期")+curTerm+wxT("记录红球<font color=red><b>")+arrary2string(missball)+wxT("</font>没有出现在历史同期<u>遗漏红球</u>记录中!");
//    if(matchball.GetCount()>0)
//    message = message + wxT("<br>当前期")+curTerm+wxT("记录红球<font color=red><b>")+arrary2string(matchball)+wxT("</font>出现在历史同期<u>遗漏红球</u>记录中!");

}
*/
//statics 1
if(lastTerm!=wxEmptyString)
{
wxString configrg=readConfigItem(wxT("Global/range"));
long range=55;
debug(wxT("配置文件中的范围:")+configrg);
if(configrg !=wxEmptyString)
{
     configrg.ToLong(&range,10);
}
debug(configrg+wxT(" 转换后配置文件中的范围:")+wxString::Format(wxT("%d"),range));

message = message +wxT("<br>上一期:<b>")+lastTerm+wxT("的mate统计:</b>");
wxString numbermate = wxEmptyString;//findNumberMate(lastTerm,range);
int i=0;
//for(int i=0;i<55;i++)
//{
 numbermate = formatNumberMate(lastTerm,range+i);
message = message+wxT("<br>")+wxString::Format(wxT("%02d"),range+i)+numbermate;
//}
//得到所有的数字mate
 numbermate = formatALLNumberMate(range+i);
message = message+wxT("<br>")+wxString::Format(wxT("%02d"),range+i)+numbermate;

//wxLogMessage(numbermate);

wxString getLastRed=wxT("SELECT * FROM _DBHISTORY where term='")+lastTerm+wxT("'");
wxLogMessage(wxT("lastterm:")+getLastRed);
db->query(getLastRed.char_str());

 if(db->nrow>0)
 {
    wxString red6 = wxString::Format(wxT("%02d"),atoi(db->records[db->ncol+7]));

    message=message+wxT("<br>根据上期最大红球数字[<font color=red>")+red6+wxT("</font>]统计下一期:<br>");
    wxString where1=wxT(" red6=")+red6;
    wxString guessSQL = wxT("select rowid+1 from _dbhistory where ")+where1;
    guessSQL = wxT("select * from _dbhistory where rowid in (")+guessSQL+wxT(") limit 0,")+wxString::Format(wxT("%d"),range);

    // wxLogMessage(guessSQL);
     db->query(guessSQL.char_str());
    Statistics* analyst;
    analyst=statisticsRecords(db);
    message = message + statis2string(db,analyst,guessSQL,false);
 }

}
delete db;


showHTMLMessage(message);
   return;
}

//F10
void patternAI()
{
wxPopupTransientWindow* ptw =NULL;
  if(BFrame->Grid1==NULL)
  {
      wxLogMessage(wxT("Grid没有激活,热键不能执行！"));
      return;
  }
if(BFrame->findBuddyLight)
{
     return;//防止多次弹出
}
wxLogMessage(wxT("准备开始计算"));
BFrame->findBuddyLight=true;
wxArrayString result;
wxGrid * grid=BFrame->Grid1;
int row=0;

    row=grid->GetCursorRow();
if(row!=0)
 {
  for(int i=2;i<grid->GetNumberCols()-1;i++)
   {
     wxString value=grid->GetCellValue(row,i);
     if(value!=wxEmptyString)
      {
    wxLogMessage(wxT(" 列值为:")+value);
      //wxLogMessage(value+wxT("\n"));
//      int intvalue=atoi(value.mb_str());
//      value=wxString::Format(wxT("%02d"),intvalue);
//      result.Add(value);
    wxFont* gFont= new wxFont(30, wxDEFAULT, wxNORMAL, wxNORMAL, 0, wxT("Sans"));
       grid->SetCellFont(row,i,*gFont);
      }
   }
 }
 BFrame->findBuddyLight=false;
}
